函数名称:strpos()
适用版本:PHP 4, PHP 5, PHP 7
函数描述:strpos() 函数用于查找字符串中第一次出现的位置,如果找到则返回第一次出现的位置,如果没有找到则返回 false。
语法:int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )
参数:
- $haystack:必需,要搜索的字符串。
- $needle:必需,要搜索的字符串。
- $offset:可选,指定搜索的起始位置,默认为 0。
返回值:
- 如果找到 needle,则返回第一次出现的位置(位置从 0 开始),如果未找到则返回 false。
示例:
$myString = "Hello, world!";
$position = strpos($myString, "world");
if ($position !== false) {
echo "The word 'world' was found at position " . $position;
} else {
echo "The word 'world' was not found in the string.";
}
输出:
The word 'world' was found at position 7
注意事项:
- strpos() 函数区分大小写,如果要进行大小写不敏感的搜索,可以使用 stripos() 函数。
- 如果 needle 是一个空字符串,strpos() 函数将返回 0。
- 如果 needle 未找到,strpos() 函数将返回 false。要使用恒等运算符(===)来检查返回值,以避免将返回值误认为是 false。